package com.ui.basic.service.admin;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsecurity.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.basic.util.ComboBoxPopulator;
import com.common.basic.util.Globals;
import com.ui.basic.command.CommandUser;
import com.ui.basic.dao.assembler.UserAsemmbler;
import com.ui.basic.ibatis.dao.CommonDAO;
import com.ui.basic.ibatis.dao.system.TblSLocDAO;
import com.ui.basic.ibatis.dao.system.TblSRoleDAO;
import com.ui.basic.ibatis.dao.system.TblSUserDAO;
import com.ui.basic.ibatis.model.system.TblSLocExample;
import com.ui.basic.ibatis.model.system.TblSRoleExample;
import com.ui.basic.ibatis.model.system.TblSUser;
import com.ui.basic.ibatis.model.system.TblSUserExample;

@Service("userService")
public class UserServiceImpl implements UserService {
	private static final transient org.apache.commons.logging.Log LOGGER = org.apache.commons.logging.LogFactory
			.getLog(UserServiceImpl.class);

	@Autowired
	private TblSUserDAO tblSUserDAO;
	@Autowired
	private TblSRoleDAO tblSRoleDAO;
	@Autowired
	private TblSLocDAO tblSLocDAO;
	@Autowired
	private CommonDAO commonDAO;

	public void setTblSUserDAO(TblSUserDAO tblSUserDAO) {
		this.tblSUserDAO = tblSUserDAO;
	}

	public void setTblSRoleDAO(TblSRoleDAO tblSRoleDAO) {
		this.tblSRoleDAO = tblSRoleDAO;
	}

	public void setTblSLocDAO(TblSLocDAO tblSLocDAO) {
		this.tblSLocDAO = tblSLocDAO;
	}

	public void setCommonDAO(CommonDAO commonDAO) {
		this.commonDAO = commonDAO;
	}

	@Transactional(readOnly = true)
	public CommandUser getUser(CommandUser commandUser) throws SQLException {
		LOGGER.debug(">>>UserServiceImpl.getUser");

		if (commandUser != null) {
			TblSUserExample example = new TblSUserExample();

			int rec = 0;
			try {
				rec = tblSUserDAO.countByExample(example);
			} catch (NullPointerException npe) {
				LOGGER.error(npe);
			}
			commandUser.calculate(rec);
			example.setIntRowNum((commandUser.getPgIndex() - 1)
					* commandUser.getPgRows());
			example.setIntRowsPerPage(commandUser.getPgRows());
			example.setOrderByClause("USERNAME");
			commandUser.setData(tblSUserDAO.selectByExample(example));
		}

		return commandUser;
	}

	@Transactional(readOnly = true)
	public CommandUser getUserDetail(CommandUser commandUser)
			throws SQLException {
		LOGGER.debug(">>>UserServiceImpl.getUserDetail");
		commandUser.setProperty(tblSUserDAO.selectByPrimaryKey(commandUser
				.getId()));
		return commandUser;
	}

	@Transactional(readOnly = true)
	public void setComboData(CommandUser commandUser) throws SQLException {
		LOGGER.debug(">>>UserServiceImpl.setComboData");
		TblSRoleExample exampleRole = new TblSRoleExample();
		exampleRole.setOrderByClause("ROLE_NAME");
		commandUser.setRoleCB(ComboBoxPopulator.populate(tblSRoleDAO
				.selectByExample(exampleRole), "id", "roleName"));

		TblSLocExample locExample = new TblSLocExample();
		locExample.setOrderByClause("LOC_NAME");
		commandUser.setLocCB(ComboBoxPopulator.populate(tblSLocDAO
				.selectByExample(locExample), "id", "locName"));

	}

	@Transactional
	public void save(CommandUser commandUser) throws SQLException {
		LOGGER.debug(">>>UserServiceImpl.save");
		UserAsemmbler assembler = new UserAsemmbler();
		TblSUser user = assembler.toEntity(commandUser);

		if(commandUser.getId() != null){
			user.setChangedby((String) (SecurityUtils.getSubject().getSession()
					.getAttribute(Globals.CURRENT_USER_NAME)));
			user.setChangeddate(new Date());
			// ***can't change userId
			user.setUsername(null);
			try {
				if (commandUser.getPassword() == null
						|| commandUser.getPassword().trim().equals(""))
					user.setPassword(null);
				else
					user.setPassword(commonDAO.convertMD5(user.getPassword()));

				tblSUserDAO.updateByPrimaryKeySelective(user);
				if (!commandUser.getPasswordStatus().booleanValue()) {
					user = tblSUserDAO.selectByPrimaryKey(user.getId());
					if (user.getLocktimestamp() != null) {
						user.setLocktimestamp(null);
						tblSUserDAO.updateByPrimaryKey(user);
					}
				}
			} catch (SQLException e) {
				LOGGER.error("***SQL Code == " + e.getErrorCode());
				LOGGER.error("***error msg == " + e.getMessage());
				throw e;
			}
		}else{
			user.setCreatedby((String) (SecurityUtils.getSubject().getSession()
					.getAttribute(Globals.CURRENT_USER_NAME)));
			user.setCreateddate(new Date());
			try {
				user.setPassword(commonDAO.convertMD5(user.getPassword()));
				tblSUserDAO.insert(user);
			} catch (SQLException e) {
				LOGGER.error("***SQL Code == " + e.getErrorCode());
				LOGGER.error("***error msg == " + e.getMessage());
				throw e;
			}
		}
	}

	public void delete(CommandUser commandUser) throws SQLException {
		LOGGER.debug(">>>UserServiceImpl.save");
		TblSUserExample example = new TblSUserExample();
		
		if(commandUser.getId()!=null){
			example.createCriteria().andIdEqualTo(commandUser.getId());
		}else if(commandUser.getSelectedRecord()!=null && commandUser.getSelectedRecord().length>0){
			List<Long> idList = new ArrayList<Long>();
			for(String strId: commandUser.getSelectedRecord())
				idList.add(Long.valueOf(strId));
			example.createCriteria().andIdIn(idList);
		}
		
		tblSUserDAO.deleteByExample(example);
	}

}
